package com.laiketui.admin.store.service.dubbo.role;

import com.laiketui.admin.store.api.role.RoleService;
import com.laiketui.common.api.PubliceService;
import com.laiketui.common.api.admin.PublicRoleService;
import com.laiketui.common.mapper.*;
import com.laiketui.common.utils.tool.cache.RedisDataTool;
import com.laiketui.common.utils.tool.data.DataCheckTool;
import com.laiketui.common.utils.tool.file.EasyPoiExcelUtil;
import com.laiketui.common.utils.tool.str.StringUtils;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DataUtils;
import com.laiketui.domain.lktconst.DictionaryConst;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.log.AdminRecordModel;
import com.laiketui.domain.mch.AdminModel;
import com.laiketui.domain.mch.CustomerModel;
import com.laiketui.domain.mch.RoleModel;
import com.laiketui.domain.role.CoreMenuModel;
import com.laiketui.domain.role.GuideMenuModel;
import com.laiketui.domain.role.RoleMenuModel;
import com.laiketui.domain.systems.SystemConfigurationModel;
import com.laiketui.domain.vo.MainVo;
import com.laiketui.domain.vo.Tool.ExcelParamVo;
import com.laiketui.domain.vo.admin.role.AddAdminVo;
import com.laiketui.domain.vo.admin.role.LoggerAdminVo;
import com.laiketui.domain.vo.role.AddRoleVo;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 权限管理
 *
 * @author Trick
 * @date 2021/1/13 12:15
 */
@Service
public class RoleServiceImpl implements RoleService {
    private final Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SystemConfigurationModelMapper systemConfigurationModelMapper;

    @Override
    public Map<String, Object> getAdminInfo(MainVo vo, Integer id) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            AdminModel admin = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            if (admin != null) {
                //判断是否是超级管理员(查看该商城所有管理员)
                boolean isSuperAdmin = admin.getType() == AdminModel.TYPE_SYSTEM_ADMIN || admin.getType() == AdminModel.TYPE_CLIENT;

                CustomerModel customerModel = customerModelMapper.selectByPrimaryKey(vo.getStoreId());
                if (customerModel == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
                }

                Map<String, Object> parmaMap = new HashMap<>(16);
                if (id != null && id > 0) {
                    parmaMap.put("id", id);
                }
                parmaMap.put("type", AdminModel.TYPE_STORE_ADMIN);
                parmaMap.put("recycle", DictionaryConst.ProductRecycle.NOT_STATUS);
                parmaMap.put("add_date_sort", "desc");
                parmaMap.put("pageStart", vo.getPageNo());
                parmaMap.put("pageEnd", vo.getPageSize());
                parmaMap.put("store_id", vo.getStoreId());
//                if (isSuperAdmin) {
//                    parmaMap.put("store_id", vo.getStoreId());
//                } else {
//                    //不是超级管理员则只能查看自己的
//                    parmaMap.put("id", admin.getId());
//                }
                int total = adminModelMapper.countAdminListInfo(parmaMap);
                List<Map<String, Object>> adminListInfo = adminModelMapper.selectAdminListInfo(parmaMap);

                resultMap.put("total", total);
                resultMap.put("list", adminListInfo);
                resultMap.put("customer_number", customerModel.getCustomer_number());
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取管理员列表 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getAdminInfo");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getRoleListInfo(MainVo vo, Integer status, Integer id) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id_pt", vo.getStoreId());
            if(status != null){
                parmaMap.put("status", status);
            }
            parmaMap.put("id", id);
            //过滤没有菜单的角色
//            parmaMap.put("existsMenu", "existsMenu");
            parmaMap.put("add_date_sort", DataUtils.Sort.DESC.toString());
            parmaMap.put("pageStart", vo.getPageNo());
            parmaMap.put("pageEnd", vo.getPageSize());

            int total = roleModelMapper.countRoleInfo(parmaMap);
            List<Map<String, Object>> roleModelList = roleModelMapper.selectRoleInfo(parmaMap);

            for (Map<String, Object> map : roleModelList) {
                int roleId = MapUtils.getIntValue(map, "id");
                Map<String, Object> parmaMap1 = new HashMap<>(16);
                parmaMap1.put("role", roleId);
                parmaMap1.put("type", AdminModel.TYPE_CLIENT);
                //获取绑定的商户
                List<Map<String, Object>> bindAdminList = adminModelMapper.getBindListInfo(parmaMap1);
                map.put("bindAdminList", bindAdminList);

            }

            resultMap.put("total", total);
            resultMap.put("list", roleModelList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取角色列表 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getRoleListInfo");
        }
        return resultMap;
    }

    @Override
    public void addAdminInfo(AddAdminVo vo) throws LaiKeAPIException {
        try {
            AdminModel admin = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            int count;
            //是否为修改
            boolean isUpdate = false;
            AdminModel adminModelOld = null;
            if (vo.getId() != null && vo.getId() > 0) {
                isUpdate = true;
                adminModelOld = new AdminModel();
                adminModelOld.setId(vo.getId());
                adminModelOld.setStore_id(vo.getStoreId());
                adminModelOld.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
                adminModelOld = adminModelMapper.selectOne(adminModelOld);
                if (adminModelOld == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_GLYBCZ, "管理员不存在", "addAdminInfo");
                }
            }
            AdminModel adminModelSave = new AdminModel();
            adminModelSave.setPassword(vo.getAdminPWD());
            adminModelSave.setRole(vo.getRoleId() + "");
            adminModelSave.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
            adminModelSave.setReal_name(vo.getRealName());
            adminModelSave.setTel(vo.getTel());
            //校验数据
            if (!isUpdate) {
                SystemConfigurationModel systemConfiguration = new SystemConfigurationModel();
                systemConfiguration.setStore_id(0);
                systemConfiguration = systemConfigurationModelMapper.selectOne(systemConfiguration);
                //添加
                AdminModel adminModel = new AdminModel();
                adminModel.setStore_id(vo.getStoreId());
                adminModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
                adminModel.setName(vo.getAdminName());
                adminModel.setReal_name(vo.getRealName());
                adminModel.setTel(vo.getTel());
                count = adminModelMapper.selectCount(adminModel);
                if (count > 0) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERRCODE_ZHYCZQCXSR, "账户已存在，请重新输入", "addAdminInfo");
                }
                //不能和超级管理员重复账号
                adminModel.setStore_id(0);
                count = adminModelMapper.selectCount(adminModel);
                if (count > 0) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERRCODE_ZHYCZQCXSR, "账户已存在，请重新输入", "addAdminInfo");
                }
                adminModelSave.setSid(admin.getId());
                adminModelSave.setType(AdminModel.TYPE_STORE_ADMIN);
                adminModelSave.setStore_id(vo.getStoreId());
                adminModelSave.setName(vo.getAdminName());
                adminModelSave.setAdd_date(new Date());
                adminModelSave.setReal_name(vo.getRealName());
                adminModelSave.setTel(vo.getTel());
                //设置默认头像
                if (systemConfiguration != null && systemConfiguration.getAdminDefaultPortrait() != null){
                    adminModelSave.setPortrait(systemConfiguration.getAdminDefaultPortrait());
                }
            } else {
                //修改
                adminModelSave.setId(adminModelOld.getId());
            }
            adminModelSave = DataCheckTool.checkAdminDataFormate(adminModelSave, isUpdate);
            if (isUpdate) {
                count = adminModelMapper.updateByPrimaryKeySelective(adminModelSave);
                publiceService.addAdminRecord(vo.getStoreId(), "修改了管理员ID：" + adminModelOld.getId() + "的信息",AdminRecordModel.Type.UPDATE, vo.getAccessId());
            } else {
                count = adminModelMapper.insertSelective(adminModelSave);
                publiceService.addAdminRecord(vo.getStoreId(), "添加了管理员名称：" + adminModelSave.getName(),AdminRecordModel.Type.ADD, vo.getAccessId());

            }

            if (count < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CZSB, "操作失败");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("添加/修改管理员信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "addAdminInfo");
        }
    }

    @Override
    public void delAdminInfo(MainVo vo, int id) throws LaiKeAPIException {
        try {
            AdminModel admin = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            if (admin.getId().equals(id)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SCSB, "删除失败");
            }
            String adminName = adminModelMapper.selectByPrimaryKey(id).getName();
            AdminModel adminModel = new AdminModel();
            adminModel.setStore_id(vo.getStoreId());
            adminModel.setId(id);

            //添加日志
            publiceService.addAdminRecord(vo.getStoreId(), "删除了管理员名称：" + adminName,AdminRecordModel.Type.DEL, vo.getAccessId());


            if (adminModelMapper.delete(adminModel) < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SCSB, "删除失败");
            }
            //踢出当前正在登录的该账号
            String logKey = GloabConst.RedisHeaderKey.LOGIN_ACCESS_MANAGE_FLAG + adminModel.getId();
            String tokenOld = redisUtil.get(logKey) + "";
            if (StringUtils.isNotEmpty(tokenOld) && redisUtil.hasKey(tokenOld)) {
                logger.debug("踢出当前正在登录的该账号 token{}", tokenOld);
                redisUtil.del(logKey);
                redisUtil.del(tokenOld);
            }

        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("删除管理员信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delAdminInfo");
        }
    }

    @Override
    public void stopAdmin(MainVo vo, int id) throws LaiKeAPIException {
        try {
            AdminModel admin = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            String event = "";
            if (admin.getId().equals(id)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CZSB, "操作失败");
            }
            AdminModel adminModel = new AdminModel();
            adminModel.setId(id);
            adminModel.setStore_id(vo.getStoreId());
            adminModel = adminModelMapper.selectOne(adminModel);
            if (adminModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_GLYBCZ, "管理员不存在");
            }
            AdminModel adminModelUpdate = new AdminModel();
            adminModelUpdate.setId(id);
            int status = adminModel.getStatus();
            if (status == AdminModel.STATUS_DISABLE) {
                status = AdminModel.STATUS_OPEN;
                event = "将管理员名称：" + adminModel.getName() + "进行了启用操作";
            } else {
                status = AdminModel.STATUS_DISABLE;
                event = "将管理员名称：" + adminModel.getName() + "进行了禁用操作";
            }
            //重置登录次数
            adminModelUpdate.setLogin_num(0);
            adminModelUpdate.setStatus(status);

            if (adminModelMapper.updateByPrimaryKeySelective(adminModelUpdate) < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CZSB, "操作失败");
            }
            //踢出当前正在登录的该账号
            String logKey = GloabConst.RedisHeaderKey.LOGIN_ACCESS_MANAGE_FLAG + adminModel.getId();
            String tokenOld = redisUtil.get(logKey) + "";
            if (StringUtils.isNotEmpty(tokenOld) && redisUtil.hasKey(tokenOld)) {
                logger.debug("踢出当前正在登录的该账号 token{}", tokenOld);
                redisUtil.del(logKey);
                redisUtil.del(tokenOld);
            }
            publiceService.addAdminRecord(vo.getStoreId(), event,AdminRecordModel.Type.OPEN_OR_CLOSE, vo.getAccessId());
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("禁用/启用管理员信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "stopAdmin");
        }
    }

    @Override
    public Map<String, Object> getAdminLoggerInfo(LoggerAdminVo vo, HttpServletResponse response) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", vo.getStoreId());
            parmaMap.put("source", AdminRecordModel.Source.PC_PLATFORM);
            parmaMap.put("add_date_sort", DataUtils.Sort.DESC.toString());
            parmaMap.put("logAccountType",vo.getLogAccountType());//日志账号类型
            parmaMap.put("logOperationType",vo.getLogOperationType());//日志操作类型
            if (!StringUtils.isEmpty(vo.getStartDate())) {
                parmaMap.put("startDate", vo.getStartDate());
                if (!StringUtils.isEmpty(vo.getEndDate())) {
                    parmaMap.put("endDate", vo.getEndDate());
                }
            }
            if (!StringUtils.isEmpty(vo.getAdminName())) {
                parmaMap.put("adminName_like", vo.getAdminName());
            }
            parmaMap.put("pageStart", vo.getPageNo());
            parmaMap.put("pageEnd", vo.getPageSize());

            List<Map<String, Object>> dataList = adminRecordModelMapper.selectAdminLoggerInfo(parmaMap);
            for (Map<String, Object> map : dataList) {
                Integer operationType= MapUtils.getIntValue(map,"type");
                String operation_type = "";
                if (operationType == AdminRecordModel.Type.LOGIN_OR_OUT){
                    operation_type = "登陆/退出";
                }else if (operationType == AdminRecordModel.Type.ADD){
                    operation_type = "添加";
                }else if (operationType == AdminRecordModel.Type.UPDATE){
                    operation_type = "修改";
                }else if (operationType == AdminRecordModel.Type.DEL){
                    operation_type = "删除";
                }else if (operationType == AdminRecordModel.Type.EXCEL_OUT){
                    operation_type = "导出";
                }else if (operationType == AdminRecordModel.Type.OPEN_OR_CLOSE){
                    operation_type = "启用/禁用";
                }else if (operationType == AdminRecordModel.Type.PASS_OR_REFUSE){
                    operation_type = "通过/拒绝";
                }else if (operationType == AdminRecordModel.Type.DEL_ORDER){
                    operation_type = "删除订单";
                }
                map.put("operation_type",operation_type);
            }
            if (vo.getExportType() == 1) {
                exportData(dataList, response);
                return null;
            }
            int total = adminRecordModelMapper.countAdminLoggerInfo(parmaMap);

            resultMap.put("list", dataList);
            resultMap.put("total", total);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取管理眼日志列表 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getAdminLoggerInfo");
        }
        return resultMap;
    }

    /**
     * 导出管理员日志信息
     *
     * @param list     -
     * @param response -
     * @throws LaiKeAPIException-
     * @author Trick
     * @date 2021/7/29 10:22
     */
    private void exportData(List<Map<String, Object>> list, HttpServletResponse response) throws LaiKeAPIException {
        try {
            //表头
            String[] headerList = new String[]{"账号ID","账号名称","账号类型","操作类型", "操作说明", "操作时间"};
            //对应字段
            String[] kayList = new String[]{"admin_id","admin_name","account_type","operation_type", "event", "add_date"};
            ExcelParamVo vo = new ExcelParamVo();
            vo.setTitle("管理员日志");
            vo.setHeaderList(headerList);
            vo.setValueList(kayList);
            vo.setList(list);
            vo.setResponse(response);
            vo.setNeedNo(true);
            EasyPoiExcelUtil.excelExport(vo);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("导出管理员日志信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "exportData");
        }
    }

    @Override
    public boolean delAdminLogger(MainVo vo, String ids) throws LaiKeAPIException {
        try {
            AdminModel adminModel = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            if (StringUtils.isEmpty(ids)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_BNWK, "id不能为空");
            }
            List<String> idList = Arrays.asList(ids.split(","));

            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", vo.getStoreId());
            parmaMap.put("idList", idList);

            publiceService.addAdminRecord(vo.getStoreId(),"将管理员日志进行了批量删除操作",AdminRecordModel.Type.DEL, vo.getAccessId());
            return adminRecordModelMapper.delAdminLoggerInfo(parmaMap) > 0;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("删除管理员日志信息 异常" + e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delAdminLogger");
        }
    }

    @Override
    public Map<String, Object> getUserRoleInfo(MainVo vo, Integer id, boolean isPt) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            AdminModel adminModel = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            List<Map<String, Object>> menuList = publicRoleService.getRoleTreeList(vo.getStoreId(), id, adminModel.getId(), isPt);
            resultMap.put("menuList", menuList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取权限列表信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getUserRoleInfo");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getUserRoles(MainVo vo, Integer roleId) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            AdminModel adminModel = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            if (roleId != null) {
                resultMap.put("roleId", roleId);
            } else {
                //获取当前用户权限id
                resultMap.put("adminName", adminModel.getName());
                resultMap.put("roleId", adminModel.getRole());
            }

            //获取商城权限下拉
            RoleModel roleModel = new RoleModel();
            roleModel.setStore_id(vo.getStoreId());
            roleModel.setStatus(RoleModel.STATUS_ROLE);

            Map<String, Object> paramMap = new HashMap<>(16);
            paramMap.put("store_id", vo.getStoreId());
            paramMap.put("status", RoleModel.STATUS_ROLE);
            paramMap.put("existsMenu", "existsMenu");
            List<Map<String, Object>> roleModelList = roleModelMapper.selectRoleInfo(paramMap);

            resultMap.put("roleList", roleModelList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取权限下拉信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getUserRoles");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getUserRoleMenuInfo(MainVo vo) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            resultMap.put("menuList", publicRoleService.getMenuTreeList(null));
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取权限菜单信息 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getUserRoleMenuInfo");
        }
        return resultMap;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUserRoleMenu(AddRoleVo vo, Integer id) throws LaiKeAPIException {
        try {
            AdminModel userCache = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            int count;
            //是否是平台操作
            if (RoleModel.STATUS_CLIENT.equals(vo.getStatus())) {
                vo.setStoreId(0);
            }
            RoleModel roleModelOld = null;
            if (id != null && id > 0) {
                roleModelOld = roleModelMapper.selectByPrimaryKey(id);
                if (roleModelOld == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_JSBCZ, "角色不存在");
                }
            }
            if (StringUtils.isEmpty(vo.getRoleName())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_JSMCBNWK, "角色名称不能为空");
            }
            if (vo.getRoleName().length() > 20) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_JSMCBNCGGZWZZD, "角色名称不能超过20个中文字长度");
            }
            if (vo.getPermissions() == null || vo.getPermissions().size() < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QXZBDQX, "请选择绑定权限");
            }
            //54457
/*            if (StringUtils.isEmpty(vo.getDescribe())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_JSMSBNWK, "角色描述不能为空");
            }*/
            if (vo.getStatus() == null || vo.getStatus() < 0) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_ZTBNWK, "状态不能为空");
            }
            if (roleModelOld == null || !roleModelOld.getName().equals(vo.getRoleName())) {
                //角色名称是否存在
                RoleModel roleModel = new RoleModel();
                roleModel.setStore_id(vo.getStoreId());
                roleModel.setName(vo.getRoleName());
                count = roleModelMapper.selectCount(roleModel);
                if (count > 0) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_JSMCYCZ, "角色名称已存在");
                }
            }
            RoleModel roleModelSave = new RoleModel();
            roleModelSave.setName(vo.getRoleName());
            roleModelSave.setRole_describe(vo.getDescribe());
            if (vo.getStatus() != null && vo.getStatus() > 0) {
                roleModelSave.setStatus(vo.getStatus());
            }

            //获取平台菜单id
            CoreMenuModel coreMenuSystem = coreMenuModelMapper.getSystemMenu();
            if (coreMenuSystem == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CDSJCW, "菜单数据错误");
            }

            //获取修改了的
            if (roleModelOld != null) {
                //修改
                roleModelSave.setId(roleModelOld.getId());
                //删除之前权限菜单
                count = roleMenuModelMapper.deleteMenu(roleModelOld.getId(), coreMenuSystem.getId());
                logger.debug("一共删除权限菜单 {} 个", count);

                //删除之前的权限导览
                count = guideMenuModelMapper.deleteGuidMenu(coreMenuSystem.getId(), roleModelOld.getId());
                logger.debug("一共删除权限菜单(功能导览) {} 个", count);
                count = roleModelMapper.updateByPrimaryKeySelective(roleModelSave);
                if (count < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLFM, "网络繁忙");
                }
                //修改角色权限,绑定的商城管理员踢出登录
                //商城默认管理员
                AdminModel adminModel = new AdminModel();
                adminModel.setRole(id + "");
                adminModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
                adminModel.setType(AdminModel.TYPE_CLIENT);
                List<AdminModel> adminModelList = adminModelMapper.select(adminModel);
                if (adminModelList != null){
                    adminModelList.forEach(adminModel1 -> {
                        String logKey = GloabConst.RedisHeaderKey.LOGIN_ACCESS_MANAGE_FLAG + adminModel1.getId();
                        String tokenOld = redisUtil.get(logKey) + "";
                        if (StringUtils.isNotEmpty(tokenOld)) {
                            //踢人
                            logger.info("修改权限,【{}】踢出登录", adminModel1.getName());
                            redisUtil.del(logKey);
                            redisUtil.del(tokenOld);
                        }
                        //踢出下级管理员-->修改平台-》权限管理-》角色列表
                        AdminModel adminModelSid = new AdminModel();
                        adminModelSid.setStore_id(adminModel1.getStore_id());
                        adminModelSid.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
                        adminModelSid.setType(AdminModel.TYPE_STORE_ADMIN);
                        List<AdminModel> adminModels = adminModelMapper.select(adminModelSid);
                        adminModels.forEach(adminModel2 -> {
                            String sidLogKey = GloabConst.RedisHeaderKey.LOGIN_ACCESS_MANAGE_FLAG + adminModel2.getId();
                            String sidTokenOld = redisUtil.get(sidLogKey) + "";
                            if (StringUtils.isNotEmpty(sidTokenOld)) {
                                //踢人
                                logger.info("修改权限,【{}】踢出登录", adminModel2.getName());
                                redisUtil.del(sidLogKey);
                                redisUtil.del(sidTokenOld);
                            }
                        });
                    });
                }
                //添加操作日志
                publiceService.addAdminRecord(vo.getStoreId(), "修改了角色名称："+roleModelSave.getName()+"的权限",AdminRecordModel.Type.UPDATE, vo.getAccessId());
            } else {
                //保存
                roleModelSave.setStore_id(vo.getStoreId());
                roleModelSave.setAdd_date(new Date());
                count = roleModelMapper.insertSelective(roleModelSave);
                //添加操作日志
                publiceService.addAdminRecord(vo.getStoreId(), "添加了角色名称："+roleModelSave.getName(), AdminRecordModel.Type.ADD, vo.getAccessId());
            }
            if (count < 1) {
                logger.info("修改/保存角色失败");
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLFM, "网络繁忙");
            }
            //保存菜单信息
            int guideSort = 0;
            //获取所有插件的menuId
            //用于判断是否给插件权限
            HashMap<Integer, Boolean> plugIsOKMap = new HashMap<>();
            for (Integer menuId : coreMenuModelMapper.getAllPlugMenuId()) {
                plugIsOKMap.put(menuId, false);
            }
            RoleMenuModel roleMenuModel = new RoleMenuModel();
            roleMenuModel.setRole_id(roleModelSave.getId());
            //保存功能导览
            GuideMenuModel guideMenuModel = new GuideMenuModel();
            guideMenuModel.setStore_id(vo.getStoreId());
            guideMenuModel.setRole_id(roleModelSave.getId());
            for (Integer menuId : vo.getPermissions()) {
                //权限菜单
                roleMenuModel.setMenu_id(menuId);
                //判断之前是否有权限对应的菜单,如果存在则不操作
                if (roleMenuModelMapper.selectCount(roleMenuModel) < 1) {
                    roleMenuModel.setAdd_date(new Date());
                    roleMenuModelMapper.insertSelective(roleMenuModel);
                }
//                roleMenuModel.setAdd_date(new Date());
//                roleMenuModelMapper.insertSelective(roleMenuModel);
                //导览菜单
                guideMenuModel.setId(null);
                guideMenuModel.setMenu_id(menuId);
                //判断导览是否存在,存在了则不添加
                count = guideMenuModelMapper.selectCount(guideMenuModel);
                if (count == 0) {
                    //排序
                    guideMenuModel.setGuide_sort(guideSort);
                    guideMenuModel.setAdd_date(new Date());
                    guideMenuModelMapper.insertSelective(guideMenuModel);
                    guideSort++;
                }
                if (plugIsOKMap.containsKey(menuId)){
                    plugIsOKMap.put(menuId, true);
                }
            }
            AdminModel adminModel = new AdminModel();
            adminModel.setRole(roleModelSave.getId() + "");
            adminModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
            adminModel.setType(AdminModel.TYPE_CLIENT);
            List<AdminModel> adminModelList = adminModelMapper.select(adminModel);
            CoreMenuModel coreMenuModel;
            for (Map.Entry<Integer, Boolean> plugBooleanEntry : plugIsOKMap.entrySet()) {
                coreMenuModel = coreMenuModelMapper.selectByPrimaryKey(plugBooleanEntry.getKey());
                String pluginCode = "";
                switch (coreMenuModel.getModule()){
                    case "coupons": pluginCode = "coupon";
                        break;
                    case "stores": pluginCode = "mch";
                        break;
                    case "seckill": pluginCode = "seconds";
                        break;
                    case "integralMall": pluginCode = "integral";
                        break;
                    case "preSale": pluginCode = "presell";
                        break;
                    case "group": pluginCode = "go_group";
                        break;
                    case "discountSetInfo":
                        pluginCode = "flashsale";
                        break;
                    default:
                        pluginCode = coreMenuModel.getModule();
                }
                for (AdminModel model : adminModelList) {
                    if (model.getStore_id() == 0){
                        continue;
                    }
                    if (plugBooleanEntry.getValue()){
                        pluginsModelMapper.updateFlagByPluginCodeAndStoreId(model.getStore_id(), pluginCode, DictionaryConst.WhetherMaven.WHETHER_NO);
                    }else {
                        pluginsModelMapper.updateFlagByPluginCodeAndStoreId(model.getStore_id(), pluginCode, DictionaryConst.WhetherMaven.WHETHER_OK);
                    }
                }
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("添加/编辑角色信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "addUserRoleMenu");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delUserRoleMenu(MainVo vo, int id) throws LaiKeAPIException {
        try {
            AdminModel userCache = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            //权限是否绑定
            AdminModel adminModel = new AdminModel();
            adminModel.setRole(id + "");
            adminModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
            int count = adminModelMapper.selectCount(adminModel);
            if (count > 0) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QXJCBDGXZJXSCCZ, "请先解除绑定关系,再进行删除操作!");
            }
            CoreMenuModel coreMenuSystem = coreMenuModelMapper.getSystemMenu();
            //删除对应角色
            RoleModel roleModel = roleModelMapper.selectByPrimaryKey(id);
            count = roleModelMapper.deleteByPrimaryKey(roleModel.getId());
            if (count < 1) {
                logger.debug("角色删除失败 roleId:{}", id);
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLFM, "网络繁忙");
            }
            //删除之前权限菜单
            count = roleMenuModelMapper.deleteMenu(id, coreMenuSystem.getId());
            logger.info("一共删除权限菜单 {} 个", count);
//            if (count < 1) {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLFM, "网络繁忙");
//            }
            //删除之前的权限导览
            count = guideMenuModelMapper.deleteGuidMenu(coreMenuSystem.getId(), id);
            logger.info("一共删除权限菜单(功能导览) {} 个", count);
//            if (count < 1) {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLFM, "网络繁忙");
//            }
            //添加操作日志
            publiceService.addAdminRecord(vo.getStoreId(), "删除了角色名称："+roleModel.getName(),AdminRecordModel.Type.DEL, vo.getAccessId());
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("删除角色信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delUserRoleMenu");
        }
    }


    @Autowired
    private PublicRoleService publicRoleService;

    @Autowired
    private CustomerModelMapper customerModelMapper;

    @Autowired
    private AdminModelMapper adminModelMapper;

    @Autowired
    private RoleModelMapper roleModelMapper;

    @Autowired
    private AdminRecordModelMapper adminRecordModelMapper;

    @Autowired
    private RoleMenuModelMapper roleMenuModelMapper;

    @Autowired
    private GuideMenuModelMapper guideMenuModelMapper;

    @Autowired
    private CoreMenuModelMapper coreMenuModelMapper;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    private PluginsModelMapper pluginsModelMapper;
}

